<?php
/**
 * Zend Image Manipulation Module
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.

 * @category   Zimm
 * @package    Zimm
 * @copyright  Copyright (c) 2012 Kristoffer Ingemansson
 * @license    New BSD License
 * @version    $Id: Instructions.php 4 2012-04-14 12:59:16Z kristoffer.ingemansson@gmail.com $
 */

class Zimm_Model_DbTable_Instructions extends Zend_Db_Table_Abstract
{
    /**
     * The table name.
     *
     * @var string
     */
    protected $_name = 'zimm_instructions';

    /**
     * Classname for row.
     *
     * @var string
     */
    protected $_rowClass = 'Zimm_Model_DbTable_Instruction_Null';

    /**
     * Builds an instruction from database complete with child instructions.
     *
     * @param  integer $instructionId
     * @return Zimm_Model_DbTable_Instruction_Abstract
     */
    public function fetchInstruction($instructionId)
    {
        static $cache = array();
        if (isset($cache[$instructionId])) {
            return $cache[$instructionId];
        }

        static $stmt = NULL;
        if (!$stmt ) {
            $name = $this->_name;
            $select = $this->select()
                ->from(array("a0"=>$name))
                ->setIntegrityCheck(false);

            $where = array('?');
            $select->joinLeft(array("a1"=>$name), "a1.instructionParentId=?", array());

            foreach (range(1, 5) as $n) {
                $select->joinLeft(array("a" . ($n+1)=>$name),
                        "a" . ($n+1) . ".instructionParentId=a$n.instructionId",
                        array());
                $where[] = "a$n.instructionId";
            }
            $select->where('a0.instructionId IN(' . implode(', ', $where) . ')')
                ->group('a0.instructionId')
                ->order('a0.dataSortOrder');

            $stmt = $this->getAdapter()->prepare($select);
        }

        $stmt->execute(array($instructionId, $instructionId));
        $rows = $stmt->fetchAll();
        $rowMap = array();
        $instruction = NULL;
        foreach ($rows as &$row) {
            $id = $row['instructionId'];
            $rowMap[$row['instructionParentId']][$id] = &$row;
            $row['_instructions'] = &$rowMap[$id];
            if (!$instruction && $id == $instructionId) {
                $instruction = &$row;
            }
        }

        if (!$instruction) {
            return $cache[$instructionId] = NULL;
        }

        $className = $this->_rowClass;
        if ($x = $instruction['instructionClassName']) {
            if (!strpos($x, '_')) {
                $x = 'Zimm_Model_DbTable_Instruction_' . $x;
            }
            $className = $x;
        }

        $data = array(
            'table'=>$this,
            'data'=>$instruction,
            'readOnly'=>false,
            'stored'=>true,
        );

        return $cache[$instructionId] = new $className($data);
    }

    /**
     * Gets file extension from instructionId.
     *
     * @param integer $instructionId
     * @return string
     */
    public static function getInstructionExtension($instructionId)
    {
        static $cache = array();
        if (!isset($cache[$instructionId])) {
            static $m = NULL;
            if (!$m) {
                $m = new self();
            }

            if ($instruction = $m->fetchInstruction($instructionId)) {
                $cache[$instructionId] = $instruction->getExtension();
            } else {
                $cache[$instructionId] = false;
            }
        }
        return $cache[$instructionId];
    }

    /**
     * Initialize database adapter.
     * Fetches the database parameters from the multidb resource.
     *
     * @return void
     */
    protected function _setupDatabaseAdapter()
    {
        if (!Zend_Registry::isRegistered('Zimm_Model_DbTable.db') || !$this->_db = Zend_Registry::get('Zimm_Model_DbTable.db')) {
            $bootstrap = Zend_Controller_Front::getInstance()->getParam('bootstrap');
            $multidb = $bootstrap->getPluginResource('multidb');
            Zend_Registry::set('Zimm_Model_DbTable.db', $this->_db = $multidb->getDb('zimm'));
        }
    }
}